import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { JWT_SECRET } from '../config/constants';

// 扩展Request类型以包含user属性
declare global {
    namespace Express {
        interface Request {
            user?: {
                id: string;
                username: string;
                role: string;
            };
        }
    }
}

export const authenticate = (req: Request, res: Response, next: NextFunction) => {
    try {
        const token = req.headers.authorization?.split(' ')[1];

        if (!token) {
            return res.status(401).json({ message: '未提供认证令牌' });
        }

        const decoded = jwt.verify(token, JWT_SECRET) as {
            id: string;
            username: string;
            role: string;
        };

        req.user = decoded;
        next();
    } catch (error) {
        console.error('认证失败:', error);
        res.status(401).json({ message: '认证失败' });
    }
};

export const authorize = (roles: string[]) => {
    return (req: Request, res: Response, next: NextFunction) => {
        if (!req.user) {
            return res.status(401).json({ message: '未授权' });
        }

        if (!roles.includes(req.user.role)) {
            return res.status(403).json({ message: '权限不足' });
        }

        next();
    };
}; 